package newfragment;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.annotation.TargetApi;
import android.os.Build;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.dell.avtivity.R;
import com.google.gson.Gson;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import DealWithMd5.DealData;
import NetRequest.SendRuest;
import bean.UserInfo;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by dell on 2017/1/26.
 */

public class RegisterFragment extends Fragment {


    public RegisterFragment() {
    }

    private final String TAG = "TAG";
    private static final int SENGCODESUCESS = 1;
    private static final int SENGCODEFAILED = 2;
    private static final int CODETRUE = 3;
    private static final int CODEFALSE = 4;
    private static final int REGISTERTRUE = 5;
    private static final int REGISTERFALSE = 6;
    private static final int REGISTERED = 7;
    // UI references.
    private View focusView = null;
    private View view = null;
    private EditText codeView;
    private EditText mPasswordView;
    private EditText phoneView;
    private View mProgressView;
    private View mLoginFormView;
    private Button getKey_btn, register_btn;

    private String password = "";
    private String password_ = "";
    private String phone = "";
    private String code = "";
    private String token = "";


    private SendRuest sr = null;

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case SENGCODESUCESS:
                    Log.d(TAG, "SEND CODE :1");
                    Toast.makeText(view.getContext(), "已发送", Toast.LENGTH_SHORT).show();
                    CountDownTimer ct = new CountTimer(5000, 1000);
                    ct.start();
                    break;
                case SENGCODEFAILED:
                    Log.d(TAG, "SEND CODE :0");
                    Toast.makeText(view.getContext(), "发送失败", Toast.LENGTH_SHORT).show();
                    break;
                case CODETRUE:
                    Log.d(TAG, "CODE is true");
                    registerto(phone, password);
                    break;
                case CODEFALSE:
                    Toast.makeText(view.getContext(), "验证码错误", Toast.LENGTH_SHORT).show();
                    Log.d(TAG, "CODE is error");
                    showProgress(false);
                    break;
                case REGISTERTRUE:
                    Log.d(TAG, "register:1");
                    Toast.makeText(view.getContext(), "注册成功", Toast.LENGTH_SHORT).show();
                    mProgressView.setVisibility(View.GONE);
                    break;
                case REGISTERFALSE:
                    Log.d(TAG, "register:0");
                    Toast.makeText(view.getContext(), "网络出错了", Toast.LENGTH_SHORT).show();
                    showProgress(false);
                    break;
                case REGISTERED:
                    Toast.makeText(view.getContext(), "该手机号码已注册,请直接登录", Toast.LENGTH_SHORT).show();
                    showProgress(false);
                    break;
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, final ViewGroup container, Bundle savedInstanceState) {

        view = inflater.inflate(R.layout.fragment_register, container, false);
        mPasswordView = (EditText) view.findViewById(R.id.register_password);
        phoneView = (EditText) view.findViewById(R.id.register_mobile);
        codeView = (EditText) view.findViewById(R.id.register_code);
        getKey_btn = (Button) view.findViewById(R.id.GetNums_phone);
        register_btn = (Button) view.findViewById(R.id.register_button);
        mLoginFormView = view.findViewById(R.id.register_scrollview);
        mProgressView = view.findViewById(R.id.register_progress);
        sr = new SendRuest(view.getContext());
        /*
        注册按钮事件
         */
        register_btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                if (attemptLogin() == 2) {
                    iskeytrue(phone, code);
                }
            }
        });

             /*
            获取验证码按钮
             */
        getKey_btn.setOnClickListener(new View.OnClickListener() {
                                          @Override
                                          public void onClick(View v) {
                                              phone = phoneView.getText().toString();
                                              if (isTelValid(phone)) {
                                                  sr.SendKey_Register(phone, new Callback() {
                                                              @Override
                                                              public void onFailure(Call call, IOException e) {
                                                                  Log.d(TAG, "SEND CODE RESPONSE:0");
                                                              }

                                                              @Override
                                                              public void onResponse(Call call, Response response) throws IOException {
                                                                  String responsedata = response.body().string();
                                                                  try {
                                                                      JSONObject jsonObject = new JSONObject(responsedata);
                                                                      String status = jsonObject.getString("error_code");
                                                                      String message_ = jsonObject.getString("message");
                                                                      Log.d(TAG, "SEND CODE RESPONSE:1" + responsedata);
                                                                      if (status.equals("0")) {
                                                                          Message message = new Message();
                                                                          message.what = SENGCODESUCESS;
                                                                          handler.sendMessage(message);
                                                                      } else if (message_.equals("该手机号码已注册,请直接登录")){
                                                                          Message message = new Message();
                                                                          message.what = REGISTERED;
                                                                          handler.sendMessage(message);
                                                                      }
                                                                  } catch (JSONException E) {
                                                                      E.printStackTrace();
                                                                  }
                                                              }
                                                          }
                                                  );
                                              } else {
                                                  Toast.makeText(view.getContext(), "请填写正确的手机号码", Toast.LENGTH_SHORT).show();
                                              }

                                          }
                                      }
        );
        return view;
    }

    private int attemptLogin() {

        // Reset errors.
        codeView.setError(null);
        phoneView.setError(null);
        mPasswordView.setError(null);

        // Store values at the time of the login attempt.
        phone = phoneView.getText().toString();
        password_ = mPasswordView.getText().toString();
        password = DealData.getMd5(password_);
        code = codeView.getText().toString();
        int cancel = 0;

        // 检查密码
        if (password_ == null && TextUtils.isEmpty(password_) || isPasswordValid(password_)) {
            mPasswordView.setError(getString(R.string.error_invalid_password));
            focusView = mPasswordView;
            cancel = 1;

        }
        //检查手机  需补充
        if (TextUtils.isEmpty(phone) || !isTelValid(phone)) {
            phoneView.setError(getString(R.string.error_field_required));
            focusView = phoneView;
            cancel = 1;
        }

        //检查验证码 补充
        if (TextUtils.isEmpty(code) || isWordsValid(code)) {
            codeView.setError(getString(R.string.error_field_words_false));
            focusView = codeView;
            cancel = 1;
        }

        if (cancel == 1) {
            focusView.requestFocus();

        } else {
            cancel = 2;
            showProgress(true);
        }
        return cancel;
    }


    /*
    验证密码长度 需补充
     */
    private boolean isPasswordValid(String password) {

        return password.length() < 4;
    }

    /*
      显示进度条
     */
    @TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
    private void showProgress(final boolean show) {
//        InputMethodManager imm = (InputMethodManager) focusView.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
//        imm.hideSoftInputFromWindow(focusView.getWindowToken(), 0);


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
            int shortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);

            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
            mLoginFormView.animate().setDuration(shortAnimTime).alpha(
                    show ? 0 : 1).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
                }
            });

            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mProgressView.animate().setDuration(shortAnimTime).alpha(
                    show ? 1 : 0).setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
                }
            });
        } else {
            mProgressView.setVisibility(show ? View.VISIBLE : View.GONE);
            mLoginFormView.setVisibility(show ? View.GONE : View.VISIBLE);
        }
    }


    /*
  获取验证码倒计时
   */
    private class CountTimer extends CountDownTimer {

        /**
         * @param millisInFuture    The number of millis in the future from the call
         *                          to {@link #start()} until the countdown is done and {@link #onFinish()}
         *                          is called.
         * @param countDownInterval The interval along the way to receive
         *                          {@link #onTick(long)} callbacks.
         */
        public CountTimer(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }


        @Override
        public void onTick(long millisUntilFinished) {
            getKey_btn.setClickable(false);
            getKey_btn.setText(millisUntilFinished / 1000 + "s后可再获取");
            getKey_btn.setBackgroundResource(R.drawable.buttonunclickable);
        }

        @Override
        public void onFinish() {
            getKey_btn.setClickable(true);
            getKey_btn.setText("获取验证码");
            getKey_btn.setBackgroundResource(R.drawable.button);
        }
    }


    /*
   验证手机格式
    */
    private boolean isTelValid(String t) {
        Pattern p = Pattern.compile("^(13[0-9]|14[57]|15[0-35-9]|17[6-8]|18[0-9])[0-9]{8}$");
        Matcher m = p.matcher(t);
        return m.matches();
    }

    /*
   验证验证码合法
    */
    private boolean isWordsValid(String password) {
        return password.length() != 6;
    }

    /*
      检查验证码正确性
     */
    private void iskeytrue(final String phone, String key) {
        sr.isKeytrue(phone, key, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "iskeytrue responsefail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                try {
                    String responsedata = response.body().string();
                    JSONObject jsonObject = new JSONObject(responsedata);
                    String status = jsonObject.getString("error_code");
                    if (!status.equals("0")) {
                        Message message = new Message();
                        message.what = CODEFALSE;
                        handler.sendMessage(message);
                    } else {
                        //验证码正确，直接登录
                        Message message = new Message();
                        message.what = CODETRUE;
                        handler.sendMessage(message);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Message message = new Message();
                    message.what = CODEFALSE;
                    handler.sendMessage(message);
                } finally {

                }
            }
        });

    }

    //注册
    private void registerto(final String phone, String password) {
        sr.SendRuest_Register(phone, password, new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d(TAG, "registerto responsefail");
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                Gson gson = new Gson();
                String responsedata = response.body().string();
                UserInfo userInfo = gson.fromJson(responsedata,UserInfo.class);
                Log.d(TAG, "register success");
                try {
                    Log.d(TAG, "register success" + responsedata);
                    String status = userInfo.getError_code();
                    if (!status.equals("s")) {
                        Message message = new Message();
                        message.what = REGISTERFALSE;
                        handler.sendMessage(message);
                    } else {
                        token = userInfo.getData().getToken();
                        Message message = new Message();
                        message.what = REGISTERTRUE;
                        handler.sendMessage(message);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
